<?php

declare(strict_types=1);

namespace App\CustHub\Mapper;

use App\CustHub\Model\ChOpenWorkAgent;
use Hyperf\Cache\Annotation\Cacheable;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Model;
use Mine\Abstracts\AbstractMapper;

class ChOpenWorkAgentMapper extends AbstractMapper
{
    public function assignModel()
    {
        $this->model = ChOpenWorkAgent::class;
    }

    /**
     * @param mixed $agentId
     * @return array
     */
    #[Cacheable(prefix: 'open_work_agent_info',value: 'id_#{agentId}',ttl: 15 * 60)]
    public function getInfoById(mixed $agentId): array
    {
        $info = $this->model::where('id',$agentId)->first();
        return !empty($info) ? $info->toArray() : [];
    }

    /**
     * @param string $corpid
     * @return ChOpenWorkAgent|Model|string|Builder|null
     */
    public function getInfoByCorpid(string $corpid): ChOpenWorkAgent|Model|string|Builder|null
    {
        return $this->model::query()
            ->where('wx_corpid',$corpid)
            ->first();
    }

    /**
     * @param string $corpid
     * @param string $suiteId
     * @return Model|Builder|null
     */
    #[Cacheable(prefix: 'auth_work_agent_info',value: '#{corpid}_#{suiteId}',ttl: 15 * 60)]
    public function getInfoByCorpidAndSuiteId(string $corpid, string $suiteId): Model|Builder|null
    {
        return $this->model::where('wx_corpid',$corpid)
            ->where('wx_suite_id',$suiteId)
            ->first();
    }

    #[Cacheable(prefix: 'auth_work_agent_info',value: '#{corpid}_#{agentId}',ttl: 15 * 60)]
    public function getInfoByCorpidAndAgentId(string $corpid, string $agentId)
    {
        return $this->model::where('wx_corpid',$corpid)
            ->where('wx_agent_id',$agentId)
            ->first();
    }

    /**
     * 检查企业应用是否存在
     * @param string $corpid
     * @param int $agentId
     * @return bool
     */
    public function checkExits(string $corpid, int $agentId): bool
    {
        return $this->model::where('wx_corpid',$corpid)
            ->where('wx_agent_id',$agentId)
            ->exists();
    }

    /**
     * 删除缓存
     * @param string $authCorpid
     * @param string $suiteId
     * @return void
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     * @throws \RedisException
     */
    public function delCache(string $authCorpid,string $suiteId): void
    {
        $delKey = [];
        $keyTwo = sprintf('%sauth_work_agent_info:%s_%s', config('cache.default.prefix'), $authCorpid, $suiteId);
        $delKey[] = $keyTwo;
        redis()->del($delKey);
    }
}